package com.atguigu.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author polaris
 * @date 2021/1/21 4:34 下午
 */
@Controller
public class HelloController {

  @Value("${sso.server.url}")
  String ssoServerUrl;

  @Resource
  RestTemplate restTemplate;

  /**
   * 无需登陆能访问
   *
   * @return
   */
  @GetMapping("/hello")
  public String hello() {
    return "hello";
  }

  /**
   * 登陆能访问
   *
   * @param model
   * @param session
   * @param token   只要ssoserver登陆成功就会带上token
   * @return
   */
  @GetMapping("/boss")
  public String boss(Model model, HttpSession session,
                     @RequestParam(value = "token", required = false) String token) {

    if (!StringUtils.isEmpty(token)) {
      //登陆成功
      //TODO 去ssoserver获取当前token真正对应的用户信息
      ResponseEntity<String> forEntity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
      String body = forEntity.getBody();
      session.setAttribute("loginUser", body);
    }

    Object loginUser = session.getAttribute("loginUser");
    if (loginUser == null) {
      return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
    } else {
      List<String> emp = new ArrayList<>();
      emp.add("lqs");
      emp.add("lxl");
      emp.add("sk");
      model.addAttribute("emps", emp);
      return "list";
    }
  }
}
